package com.fyzk.activity.lottery.recommend_order;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.chongzhi.RechargeActivity;
import com.fyzk.activity.popupwindow.KeyBoardPopupwindow;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.net.Commands;
import com.fyzk.net.PublicMethod;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.view.TopTitleView;
import com.fyzk.view.ViewCallBack;
import com.tyjc.lottery.R;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.List;

import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

/**
 * Created by fanxs11 on 2017/7/5.
 * 推荐单详情(跟单)
 */

@ContentView(R.layout.ac_recommenddetail)
public class RecommendDetailActivity extends BaseActivity implements KeyBoardPopupwindow.OnKeyBoardListener {

    @ViewInject(R.id.recommenddetail_topview)
    private TopTitleView topView;

    @ViewInject(R.id.rr_detail_userinfo_ll)
    private LinearLayout userInfo_ll;
    @ViewInject(R.id.rr_detail_username_tv)
    private TextView userName_tv;
    @ViewInject(R.id.rr_detail_hittatio_tv)
    private TextView hitRatio_tv;
    @ViewInject(R.id.rr_detail_profitratio_tv)
    private TextView profitRatio_tv;
    @ViewInject(R.id.rr_detail_amount_tv)
    private TextView money_tv;
    @ViewInject(R.id.rr_detail_endtime_tv)
    private TextView endTime_tv;
    @ViewInject(R.id.rr_detail_type)
    private LinearLayout type_tv;
    @ViewInject(R.id.rr_detail_content_ll)
    private LinearLayout content_ll;

    @ViewInject(R.id.rr_detail_multiple_ll)
    private LinearLayout multiple_ll;
    @ViewInject(R.id.rr_detail_multiple_tv)
    private TextView multiple_tv;
    @ViewInject(R.id.rr_detail_with_btn2)
    private TextView with_tv;
    @ViewInject(R.id.rr_detail_money_tv)
    private TextView withMoney_tv;
    @ViewInject(R.id.rr_detail_tc_style)
    private TextView tcStyle_tv;
    @ViewInject(R.id.rr_detail_tc_pl)
    private TextView tcPl_tv;

    // 最小跟单投注彩金
    private final int MIN_TOUZHU = 20;

    private MyRecommendOrderBean infor;

    private KeyBoardPopupwindow keyBoardPopupwindow;
    private AlertDialog payDialog;
    private AlertDialog minTouZhuAlertDialog = null;
    private List<MyRecommendOrderUserBean> mGdList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        infor = (MyRecommendOrderBean) getIntent().getSerializableExtra(IntentParamUtils.RECOMMENDINFOR);

        initView();

        findRecommendedUserDetail(false);
        findRecommendedUserTcStyle(false);
    }

    private void initView() {
        topView.setOnTitleClickListener(this);

        userInfo_ll.setOnClickListener(this);
        if (infor != null) {
            if (infor.getIsexpert() == 1) {
                Drawable drawable = getResources().getDrawable(R.drawable.rr_v_icon);
                userName_tv.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
            } else {
                userName_tv.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
            }
            if (!TextUtil.isEmpty(infor.getUserName())) {
                userName_tv.setText(PublicMethod.getSenderName("", infor.getUserName()));
            }
            money_tv.setText(infor.getAmount() / infor.getMultiple() / 100 + "米");
            endTime_tv.setText("截止日期：" + infor.getEndTime());
            if (infor.getWay() != 0) {   // 方案保密
                type_tv.setVisibility(View.VISIBLE);
                content_ll.setVisibility(View.GONE);
            } else {
                type_tv.setVisibility(View.GONE);
                content_ll.setVisibility(View.VISIBLE);
                MyRecommendOrderBean.DetailBean detailBean = infor.getDetail();
                setContent(content_ll, detailBean.getRaceBetcode(), detailBean.getPlayName());
            }
        }

        with_tv.setOnClickListener(this);
        multiple_ll.setOnClickListener(this);

        withMoney_tv.setText(getMoney() / 100 + "米");

        keyBoardPopupwindow = new KeyBoardPopupwindow(getContext(), 99999, "投", "倍");
        keyBoardPopupwindow.setOnKeyBoardListener(this);
    }

    private void setContent(LinearLayout content_ll, List<MyRecommendOrderBean.DetailBean.RaceBetcodeBean> raceInfos, String playName) {
        content_ll.removeAllViews();

        View itemHeadView = LayoutInflater.from(getContext()).inflate(R.layout.view_rr_hall_head_content, null);
        content_ll.addView(itemHeadView);

        for (int i = 0; i < raceInfos.size(); i++) {
            View itemView = LayoutInflater.from(getContext()).inflate(R.layout.view_rr_hall_content, null);
            ImageView left_iv = (ImageView) itemView.findViewById(R.id.rr_hall_content_left_iv);
            RelativeLayout item_rl = (RelativeLayout) itemView.findViewById(R.id.rr_hall_content_rl);
            TextView line_tv = (TextView) itemView.findViewById(R.id.rr_hall_content_line_tv);
            TextView matchId_tv = (TextView) itemView.findViewById(R.id.rr_hall_content_matchid);
            TextView matchName_tv = (TextView) itemView.findViewById(R.id.rr_hall_content_matchname);
            TextView homeAndAway_tv = (TextView) itemView.findViewById(R.id.rr_hall_content_h_a);
            TextView betCode_tv = (TextView) itemView.findViewById(R.id.rr_hall_content_betcode_tv);

            matchName_tv.setVisibility(View.GONE);

            item_rl.setBackgroundColor(getResources().getColor(R.color.white));
            MyRecommendOrderBean.DetailBean.RaceBetcodeBean raceInfo = raceInfos.get(i);
            matchId_tv.setText(raceInfo.getOfficialWeekDay() + raceInfo.getMatchNum());
            matchName_tv.setText(raceInfo.getMatchName());
            homeAndAway_tv.setText(raceInfo.getHomeTeam() + "\n VS \n" + raceInfo.getAwayTeam());
            String betCodes = "";   // 投注内容
            String results = "";    // 比赛结果
            for (int j = 0; j < raceInfo.getContents().size(); j++) {
                betCodes += raceInfo.getContents().get(j).getBetcode() + " ";
            }
            betCode_tv.setText(Html.fromHtml(betCodes, null, null));

//            if (playName.equals("2串1")) {
//                left_iv.setImageDrawable(getResources().getDrawable(R.drawable.rr_2c1_icon));
//            } else if (playName.equals("3串1")) {
//                left_iv.setImageDrawable(getResources().getDrawable(R.drawable.rr_3c1_icon));
//            } else if (playName.equals("单关")) {
//                left_iv.setImageDrawable(getResources().getDrawable(R.drawable.rr_dan_icon));
//            } else {
//                left_iv.setImageDrawable(getResources().getDrawable(R.drawable.rr_23c1_icon));
//            }
//            if (i == 0) {
//                left_iv.setVisibility(View.VISIBLE);
//            } else {
            left_iv.setVisibility(View.GONE);
//            }
            if (i == raceInfos.size()) {
                line_tv.setVisibility(View.GONE);
            } else {
                line_tv.setVisibility(View.VISIBLE);
            }
            content_ll.addView(itemView);
        }
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.rr_detail_userinfo_ll:
                Intent intent = new Intent(getContext(), OtherCenterActivity.class);
                if (infor != null) {
                    intent.putExtra(IntentParamUtils.USERNO, infor.getUserno());
                    intent.putExtra(IntentParamUtils.RECOMMENDINFOR, infor);
                    intent.putExtra("isExpert", infor.getIsexpert());
                }
                startActivity(intent);
                finish();
                break;
            case R.id.rr_detail_multiple_ll:

                keyBoardPopupwindow.showPopupWindow(multiple_ll, multiple_tv.getText().toString());
                break;
            case R.id.rr_detail_with_btn2:
                if (!MySharedPreferences.getInstance().getLoginStatus()) {
                    AppLotteryInfos.clear();
                    ViewCallBack.getInstance().countDownObjs.clear();
                    ActivityTaskManager.getInstance().closeAllActivity();
                    intent = new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                    return;
                }

//                if (MIN_TOUZHU > getMoney() / 100) {
//                    if (minTouZhuAlertDialog == null) {
//                        minTouZhuAlertDialog = new AlertDialog.Builder(this)
//                                .setMessage("跟单投注彩金不能少于" + MIN_TOUZHU + "米")
//                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        dialog.cancel();
//                                    }
//                                }).create();
//                    }
//                    minTouZhuAlertDialog.show();
//                    return;
//                }

                double leftMoney = 0;
                try {
                    leftMoney = Double.parseDouble(MySharedPreferences.getInstance().getBalance().toString());
                } catch (Exception e) {

                }
                if (leftMoney >= getMoney() / 100) {
                    showPayDialog();
                } else {
                    showLeftMoneyLowDialog(getMoney() / 100, leftMoney);
                }
                break;
        }
    }

    /**
     * 显示是否支付对话框
     */
    public void showPayDialog() {

        if (payDialog == null) {
            payDialog = new AlertDialog.Builder(this).setTitle("温馨提示")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            followOrderBet();
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    }).create();
        }
        payDialog.setMessage("确认跟单，立即支付");
        payDialog.show();
    }

    /**
     * 获取跟单总彩金
     *
     * @return
     */
    private long getMoney() {
        long money = infor.getAmount() / infor.getMultiple() * getMultiple();
        return money;
    }

    /**
     * 获取跟单倍数
     *
     * @return
     */
    private int getMultiple() {
        int multiple = 1;
        try {
            multiple = Integer.parseInt(multiple_tv.getText().toString());
        } catch (Exception e) {

        }
        return multiple;
    }

    /**
     * 荐单个人详情查询
     *
     * @param showProgress
     */
    private void findRecommendedUserDetail(boolean showProgress) {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("userno", infor.getUserno());
            httpPostJson(CommandUtil.FINDRECOMMENDEDRANKUSERDETAIL, Commands.FINDRECOMMENDEDRANKUSERDETAIL, request_json,
                    showProgress);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void findRecommendedUserTcStyle(boolean show) {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("recommendId", infor.getRecommendId());
            httpPostJson(CommandUtil.FINDRECOMMENDEDRANKUSETCSTYLE, Commands.FINDRECOMMENDEDRANKUSETCSTYLE, request_json,
                    show);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 跟单投注
     */
    private void followOrderBet() {

        try {
            JSONObject params = new JSONObject();
            params.put("betcode", infor.getBetcode());
            params.put("lotteryType", infor.getLotteryType());
            params.put("phase", infor.getPhase());
            params.put("amount", getMoney());
            params.put("multiple", getMultiple());
            params.put("oneAmount", 2 * 100);
            params.put("prizeOptimize", "0");//prizeOptimize奖金诱惑（优化：1；普通：0）
            params.put("codeFilter", "0");//codeFilter旋转过滤（过滤：1；普通：0）
            params.put("userCouponId", "");//优惠劵Id，非优惠劵投注可以不写
            params.put("recommendId", infor.getRecommendId());
            params.put("recommendOrderId", infor.getOrderid());

            httpPostJson(CommandUtil.FOLLOWORDERBET, Commands.FOLLOWORDERBET, params, true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        switch (requestCode) {
            case CommandUtil.FINDRECOMMENDEDRANKUSERDETAIL:
                MyRecommendBean userInfor = JSON.parseObject(resultBean.getData(), MyRecommendBean.class);
                hitRatio_tv.setText(AppUtil.formatToYuanLXS(userInfor.getHitRatio() * 100) + "%");
                profitRatio_tv.setText(AppUtil.formatToYuanLXS(userInfor.getProfitRatio() * 100) + "%");
                break;
            case CommandUtil.FOLLOWORDERBET:

                new AlertDialog.Builder(getContext()).setTitle("提示").setMessage("跟单成功")
                        .setNegativeButton("完成", new DialogInterface
                                .OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                RecommendDetailActivity.this.finish();
                            }
                        }).setCancelable(false).create().show();
                break;
            case CommandUtil.FINDRECOMMENDEDRANKUSETCSTYLE:
                MyRecommendTcBean tcBean = JSON.parseObject(resultBean.getData(), MyRecommendTcBean.class);
                if (tcBean.getProportionType() == 1) {
                    tcStyle_tv.setText("按奖金分成");
                } else if (tcBean.getProportionType() == 2) {
                    tcStyle_tv.setText("按利润分成");
                } else if (tcBean.getProportionType() == 3) {
                    tcStyle_tv.setText("按投注彩金分成");
                } else {
                    tcStyle_tv.setText("");
                }
                tcPl_tv.setText(tcBean.getProportions() + "%");
                break;
        }
    }

    @Override
    protected void onFailure(int requestCode, String errorCode, String message) {
        super.onFailure(requestCode, errorCode, message);
    }

    @Override
    public void onItem(int position) {

    }

    @Override
    public void popupShow() {

    }

    @Override
    public void popupDismiss(int multiple) {
        multiple_tv.setText("" + multiple);
        withMoney_tv.setText(getMoney() / 100 + "米");
    }

    private AlertDialog leftMoneyLowDialog = null;

    /**
     * 显示彩金不足对话框
     *
     * @param money
     * @param leftMoney
     */
    public void showLeftMoneyLowDialog(double money, double leftMoney) {

        if (leftMoneyLowDialog == null) {
            leftMoneyLowDialog = new AlertDialog.Builder(this).setTitle("提示")
                    .setPositiveButton("去充值", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            Intent intent = new Intent(getContext(), RechargeActivity
                                    .class);
                            getContext().startActivity(intent);
                        }
                    }).setNegativeButton("返回", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    }).create();
        }
        leftMoneyLowDialog.setMessage("彩金不足,彩金" + leftMoney +
                "米，需支付" + money + "米，还差" + AppUtil.formatToYuanLXS(money - leftMoney) + "米");
        leftMoneyLowDialog.show();
    }
}
